//
//  PictureBrowserViewController.swift
//  SwiftWB
//
//  Created by 钟清 on 17/4/7.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit
import SVProgressHUD

class PictureBrowserViewController: UIViewController {
    /* 中图URL */
    var bmiddle_pic: [NSURL]
    /* 当前点击索引 */
    var indexPath: NSIndexPath
    init(bmiddle_pic: [NSURL], indexPath: NSIndexPath) {
        self.bmiddle_pic = bmiddle_pic
        self.indexPath = indexPath
        super.init(nibName: nil, bundle: nil)
        /* 初始化UI */
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /* 选中 */
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
    }
    
    // MARK: - 内部控制方法
    private func setupUI() {
        /* 添加控件 */
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        /* 布局 */
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView" : collectionView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView" : collectionView])
        view.addConstraints(cons)
        
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        let closeHCons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-45-[closeButton(75)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["closeButton" : closeButton])
        let closeVCons = NSLayoutConstraint.constraintsWithVisualFormat("V:[closeButton(40)]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["closeButton" : closeButton])
        view.addConstraints(closeHCons)
        view.addConstraints(closeVCons)
        
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        let saveHCons = NSLayoutConstraint.constraintsWithVisualFormat("H:[saveButton(75)]-45-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["saveButton" : saveButton])
        let saveVCons = NSLayoutConstraint.constraintsWithVisualFormat("V:[saveButton(40)]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["saveButton" : saveButton])
        view.addConstraints(saveHCons)
        view.addConstraints(saveVCons)

    }
    // MARK: - Event
    /* 关闭图片浏览器 */
    @objc private func closeButtonClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    /* 保存图片 */
    @objc private func saveButtonClick() {
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PictureBrowserCollectionViewCell
        let image = cell.imageView.image!
        // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(PictureBrowserViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    /* 监听保存图片成功与否 */
    @objc private func image(_: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject?) {
        if didFinishSavingWithError == nil { // 没有报错
            SVProgressHUD.showSuccessWithStatus("图片保存成功", maskType: SVProgressHUDMaskType.Black)
        } else { // 报错
            SVProgressHUD.showErrorWithStatus("图片保存失败", maskType: SVProgressHUDMaskType.Black)
        }
    }
    // MARK: - Lazy
    /* 自定义collectionView */
    private lazy var collectionView: UICollectionView = {
        let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: PictureBrowserFlowLayout())
        clv.dataSource = self
        clv.registerClass(PictureBrowserCollectionViewCell.self, forCellWithReuseIdentifier: "browserCell")
        return clv
    }()
    /* 关闭按钮 */
    private lazy var closeButton: UIButton = {
       let btn = UIButton()
        btn.setTitle("关闭", forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(PictureBrowserViewController.closeButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        btn.backgroundColor = UIColor(white: 0.3, alpha: 0.2)
        return btn
    }()
    /* 保存按钮 */
    private lazy var saveButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(PictureBrowserViewController.saveButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        btn.backgroundColor = UIColor(white: 0.3, alpha: 0.2)
        return btn
    }()
    

}
// MARK: - DataSource
extension PictureBrowserViewController: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bmiddle_pic.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("browserCell", forIndexPath: indexPath) as! PictureBrowserCollectionViewCell
        cell.imageURL = bmiddle_pic[indexPath.item]
        return cell
    }
}
/* 自定义流水布局 */
class PictureBrowserFlowLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        itemSize = UIScreen.mainScreen().bounds.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
    }
}
